from typing import Optional, List

from peewee import Model, CharField, IntegerField, AutoField, FloatField
from playhouse.shortcuts import model_to_dict
from pydantic import BaseModel

from db.my_sqlite import DB


# 定义文件模型
class ChatHistory(Model):
    id = AutoField(primary_key=True, help_text="历史记录id")
    userid = IntegerField(help_text="用户id")
    message = CharField(help_text="对话详情")
    title = CharField(help_text="对话标题")
    update_time = FloatField(help_text="更新时间戳")

    class Meta:
        database = DB


class ChatHistoryModel(BaseModel):
    id: Optional[int]
    userid: Optional[int]
    message: Optional[str]
    title: Optional[str]
    update_time: Optional[float]

class ChatHistoryTable:
    def __init__(self, db):
        self.db = db
        self.db.create_tables([ChatHistory])

    @staticmethod
    async def insert_new_history(
            userid: int,
            message: str,
            title: str,
            update_time: float,
    ) -> Optional[ChatHistoryModel]:
        file = ChatHistory.create(
            userid=userid,
            message=message,
            title=title,
            update_time=update_time
        )
        return ChatHistoryModel(**model_to_dict(file))

    @staticmethod
    async def update_history(
            id: int,
            userid: int,
            message: str,
            update_time: float,
    ):
        res = ChatHistory.update(
            message=message,
            update_time=update_time
        ).where(
            (ChatHistory.id == id) &
            (ChatHistory.userid == userid)
        ).execute() > 0

        return res


    @staticmethod
    async def get_chat_histories(userid: int) -> List[ChatHistoryModel]:
        files = ChatHistory.select().where(
            (ChatHistory.userid == userid)
        )

        return [ChatHistoryModel(**model_to_dict(file)) for file in files]

    @staticmethod
    def get_chat_history(userid: int, id: int) -> [Optional[ChatHistoryModel]]:
        files = ChatHistory.select().where(
            (ChatHistory.userid == userid) &
            (ChatHistory.id == id)
        )
        return [ChatHistoryModel(**model_to_dict(file)) for file in files]

    @staticmethod
    async def delete_chat_history(userid: int, id: int) -> bool:
        res = ChatHistory.delete().where(
            (ChatHistory.userid == userid) &
            (ChatHistory.id == id)
        ).execute() > 0
        return res


ChatHistories = ChatHistoryTable(DB)
